const fetch = require('node-fetch');
const config = require('../../config');

const templateCodes = {
  0: 'SMS_107000076',
  1: 'SMS_106890071',
  2: 'SMS_107080088',
  3: 'SMS_106920098'
};

export default class SmsService {
  public static async sendSms(smsParams, type, mobileTo) {
    try {
      const templateCode = templateCodes[type];
      const querystring = require('querystring');
      const form = {
        ParamString: JSON.stringify(smsParams),
        TemplateCode: templateCode,
        RecNum: mobileTo,
        SignName: '游呗之旅'
      };
      const query = querystring.stringify(form);
      const url = `http://sms.market.alicloudapi.com/singleSendSms?${query}`;
      const response = await fetch(url, {
        headers: {
          Authorization: `APPCODE ${config.sms.appCode}`
        }
      });
      if (response.status !== 200) {
        throw new Error('系统错误');
      }
      const result = await response.json();
      if (!result.success) {
        throw new Error(result.message);
      }
      return true;
    } catch (err) {
      throw err;
    }
  }
}
